import Koa from 'koa'
import dbConfig from '../config/dbConfig'
import errors from './HttpException'
import {catchError} from '../middlewares/exception'
import path from 'path'
import staticFiles from 'koa-static'
import cors from 'koa2-cors'
import Utils from '../common/utils/Utils'
import session from 'koa-session'
import config from '../config/config'
import socket from "socket.io"
import http from 'http'
import logger from '../middlewares/logs'
import log4js from 'log4js'
class Init{
    public static app: Koa<Koa.DefaultState, Koa.DefaultContext>
    public static server: http.Server
    public static initCore(app: Koa<Koa.DefaultState, Koa.DefaultContext>, server: http.Server) {
        Init.app = app
        Init.server = server
        console.log(Init)
        //Init.initGlobalVariable()
        Init.loadCrossDomain()
        Init.initCatchError()
        Init.loadStatic()
        Init.loadSession()
        Init.initLoadRouters()
        Init.loadSession()
        Init.loadSocket()
        // Init.initLogs()
    }

    public static initGlobalVariable(){
        const globalAny: any = global
        
        globalAny.dbConfig = dbConfig
        globalAny.errors = errors
        /* global.dbConfig = dbConfig
        global.errors = errors  */
    }

    
    public static initCatchError(){
        
        Init.app.use(catchError)
    }

    public static loadStatic () {
        Init.app.use(staticFiles(path.join(`${process.cwd()}/${config.base}/public/`)))
    }

    static loadCrossDomain () {
        Init.app.use(cors())
    }

    static async initLoadRouters() {
        const dirPath = path.join(`${process.cwd()}/${config.base}/api/`)
        await Utils.fileDisplay(dirPath,Init.app)
        console.log('接口加载完成')
    }


    // 加载session
    static loadSession () {
        
        Init.app.keys = ['some secret hurr'];
        Init.app.use(session({
            key: 'koa:sess',   //cookie key (default is koa:sess)
            maxAge: 86400000,  // cookie的过期时间 maxAge in ms (default is 1 days)
            overwrite: true,  //是否可以overwrite    (默认default true)
            httpOnly: true, //cookie是否只有服务器端可以访问 httpOnly or not (default true)
            signed: true,   //签名默认true
            rolling: false,  //在每次请求时强行设置cookie，这将重置cookie过期时间（默认：false）
            renew: false,  //(boolean) renew session when session is nearly expired,
        },Init.app));
    }

    static loadSocket(){
        const io = new socket.Server(this.server)
        // const io = require('socket.io')(this.server);
        io.on('connection', (socket: { on: (arg0: string, arg1: (data: any) => void) => void; emit: (arg0: string, arg1: { hello: string }) => void }) => {
            console.log('socket初始化完成');
            socket.on('say', data => {
                console.log(data, '接收到的信息')
                socket.emit('message', {hello: '你是谁'})
            })
            socket.on('disconnect', () => {
                console.log('user disconnected');
              });
        })
        // io.on('connection', (socket) => {
        //     socket.on('chat message', (msg) => {
        //     console.log('message: '+msg);
        //     io.emit('chat message', msg);
        // });
        // socket.on('disconnect', () => {
        //     console.log('user disconnected');
        //   });
    }

    // static initLogs (){
    //     Init.app.use(log4js.connectLogger(logger, {level: 'auto', format:':method :url'}));
    // }
}

export default Init.initCore



